import React, { PureComponent } from 'react';
import { Modal, Form, Row, Input, DatePicker, Radio, Select } from 'antd';
// import { connect } from 'dva';
import lodash from 'lodash';
import moment from 'moment';
import { existsUserByUsername, existsUserByTelephone, existsUserByEmail } from '../../services/manage-by-query-controller';
import { UserTypeArray, LockedArray, EnabledArray } from '../../utils/enum';
// import classNames from 'classnames';
import styles from './UserManageAdd.less';

@Form.create()
export default class UserManageAdd extends PureComponent {

  onCreate = () => {
    const { form, onOk } = this.props;
    if (!(onOk instanceof Function)) return;
    form.validateFields((err, formValues) => {
      if (err) return;
      const userData = formValues;
      if (userData.expiredTime) {
        userData.expiredTime = moment(userData.expiredTime).format('YYYY-MM-DD 00:00:00');
      }
      onOk(userData);
    });
  }

  render() {
    const { userData, sysNameList, saveForm, visible, confirmLoading, onCancel, form } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    if (saveForm instanceof Function) saveForm(form);
    const width = 200;
    return (
      <Modal
        width={670}
        visible={visible}
        confirmLoading={confirmLoading}
        title="新增用户"
        okText="确定"
        onCancel={onCancel}
        onOk={this.onCreate}
        maskClosable={false}
        bodyStyle={{ padding: '24px 24px 0 24px' }}
      >
        <Form layout="inline" className={styles.form}>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="登录名" hasFeedback>
              {getFieldDecorator('username', {
                initialValue: userData ? userData.username : undefined,
                validateFirst: true,
                // validateTrigger: 'onBlur',
                rules: [
                  { required: true, whitespace: true, pattern: /^[a-zA-Z0-9_-]{3,16}$/, message: '3-16字符(数字、字母、下划线)' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (!value || lodash.trim(value) === '') callback(errors);
                      existsUserByUsername(value).then(({ result }) => {
                        if (result) {
                          errors.push("登录名已经存在!");
                        }
                        callback(errors);
                      });
                    },
                  },
                ],
              })(
                <Input placeholder="登录名" style={{ width }} />
              )}
            </Form.Item>
            <Form.Item label="手机号" hasFeedback>
              {getFieldDecorator('telephone', {
                initialValue: userData ? userData.telephone : undefined,
                validateFirst: true,
                // validateTrigger: 'onBlur',
                rules: [
                  { required: false, whitespace: true, pattern: /^1[0-9]{10}$/, message: '手机号格式不正确' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (!value || lodash.trim(value) === '') callback(errors);
                      existsUserByTelephone(value).then(({ result }) => {
                        if (result) {
                          errors.push("手机号已经存在!");
                        }
                        callback(errors);
                      });
                    },
                  },
                ],
              })(
                <Input placeholder="手机号" style={{ width }} />
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="登录密码" required hasFeedback>
              {getFieldDecorator('password', {
                initialValue: userData ? userData.password : undefined,
                rules: [
                  { required: true, whitespace: false, min: 6, max: 16, message: '登录密码长度必须6~16字符' },
                ],
              })(
                <Input type="password" placeholder="登录密码" style={{ width }} />
              )}
            </Form.Item>
            <Form.Item label="确认密码" required hasFeedback>
              {getFieldDecorator('passwordConfirm', {
                initialValue: userData ? userData.passwordConfirm : undefined,
                rules: [
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      const password = getFieldValue('password');
                      const passwordLength = password ? password.length : 0;
                      const valueLength = value ? value.length : 0;
                      if (!value || value.length <= 0) {
                        errors.push("密码不能为空");
                      } else if (password !== value || passwordLength !== valueLength) {
                        errors.push("两次输入的密码不一致");
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Input type="password" placeholder="确认密码" style={{ width }} />
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="用户邮箱" hasFeedback>
              {getFieldDecorator('email', {
                initialValue: userData ? userData.email : undefined,
                validateFirst: true,
                // validateTrigger: 'onBlur',
                rules: [
                  { required: false, whitespace: true, pattern: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/, message: '邮箱格式不正确' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (!value || lodash.trim(value) === '') callback(errors);
                      existsUserByEmail(value).then(({ result }) => {
                        if (result) {
                          errors.push("邮箱已经存在!");
                        }
                        callback(errors);
                      });
                    },
                  },
                ],
              })(
                <Input placeholder="用户邮箱" style={{ width }} />
              )}
            </Form.Item>
            <Form.Item label="过期时间">
              {getFieldDecorator('expiredTime', {
                initialValue: (userData && userData.expiredTime) ? moment(userData.expiredTime) : undefined,
                rules: [
                  { required: false, message: '过期时间不能为空' },
                ],
              })(
                <DatePicker placeholder="过期时间" style={{ width }} />
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="归属系统">
              {getFieldDecorator('sysNameList', {
                initialValue: userData ? userData.sysNameList : undefined,
                rules: [
                  // { required: false, whitespace: true, message: '归属系统' },
                ],
              })(
                <Select placeholder="归属系统" mode="tags" tokenSeparators={[',']} style={{ width: 505 }}>
                  {sysNameList.map(item => (<Select.Option key={item} value={item}>{item}</Select.Option>))}
                </Select>
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="说明" style={{ marginBottom: 0 }}>
              {getFieldDecorator('description', {
                initialValue: userData ? userData.description : undefined,
              })(
                <Input.TextArea placeholder="说明" rows={2} autosize={{ minRows: 2, maxRows: 3 }} style={{ width: 505, maxWidth: 1000 }} />
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="用户类型">
              {getFieldDecorator('userType', {
                initialValue: userData ? userData.userType : undefined,
                rules: [
                  { required: true, whitespace: true, message: '用户类型不能为空' },
                ],
              })(
                <Radio.Group placeholder="用户类型">
                  {UserTypeArray.map(item => (<Radio key={item.value} value={item.value}>{item.label}</Radio>))}
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label="是否锁定">
              {getFieldDecorator('locked', {
                initialValue: userData ? userData.locked : undefined,
                rules: [
                  { required: true, whitespace: true, message: '是否锁定不能为空' },
                ],
              })(
                <Radio.Group placeholder="是否锁定">
                  {LockedArray.map(item => (<Radio key={item.value} value={item.value}>{item.label}</Radio>))}
                </Radio.Group>
              )}
            </Form.Item>
          </Row>

          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="是否启用">
              {getFieldDecorator('enabled', {
                initialValue: userData ? userData.enabled : undefined,
                rules: [
                  { required: true, whitespace: true, message: '是否启用不能为空' },
                ],
              })(
                <Radio.Group placeholder="是否启用">
                  {EnabledArray.map(item => (<Radio key={item.value} value={item.value}>{item.label}</Radio>))}
                </Radio.Group>
              )}
            </Form.Item>
          </Row>
        </Form>
      </Modal>
    );
  }
}
